#!/bin/bash

# DaoHang项目宝塔部署脚本

echo "开始部署DaoHang项目..."

# 项目信息
PROJECT_NAME="DaoHang"
PROJECT_PATH="/www/wwwroot/daohang"
SERVICE_NAME="daohang"
DB_PATH="$PROJECT_PATH/daohang.db"

# 停止现有服务
echo "停止现有服务..."
systemctl stop $SERVICE_NAME 2>/dev/null || true

# 创建项目目录
echo "创建项目目录..."
mkdir -p $PROJECT_PATH
cd $PROJECT_PATH

# 创建数据库目录并设置权限
echo "创建数据库目录并设置权限..."
mkdir -p $(dirname $DB_PATH)
touch $DB_PATH 2>/dev/null || true  # 尝试创建数据库文件

# 设置目录和文件权限
echo "设置文件权限..."
chown -R www:www $PROJECT_PATH
chmod -R 755 $PROJECT_PATH
chmod 644 $DB_PATH 2>/dev/null || true  # 数据库文件权限

# 确保www用户对数据库目录有写权限
chmod 755 $(dirname $DB_PATH)
chown www:www $(dirname $DB_PATH)

# 发布项目（在开发机器上执行）
echo "请在开发机器上执行以下命令发布项目："
echo "dotnet publish -c Release -o ./publish --self-contained false --runtime linux-x64"
echo ""
echo "然后将publish文件夹内容上传到: $PROJECT_PATH"
echo ""

# 设置执行权限
chmod +x $PROJECT_PATH/$PROJECT_NAME 2>/dev/null || true

# 创建systemd服务文件
echo "创建systemd服务..."
cat > /etc/systemd/system/$SERVICE_NAME.service << EOF
[Unit]
Description=DaoHang Web Application
After=network.target

[Service]
Type=notify
WorkingDirectory=$PROJECT_PATH
ExecStart=$PROJECT_PATH/$PROJECT_NAME
Restart=always
RestartSec=5
User=www
Group=www
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=ASPNETCORE_URLS=http://127.0.0.1:5000

# 确保服务有足够的权限访问数据库
UMask=0022

[Install]
WantedBy=multi-user.target
EOF

# 重新加载systemd配置
systemctl daemon-reload

# 启用并启动服务
echo "启动服务..."
systemctl enable $SERVICE_NAME

# 在启动服务前，再次确认权限设置
echo "最终权限检查..."
chown -R www:www $PROJECT_PATH
chmod -R 755 $PROJECT_PATH
# 确保数据库文件和目录权限正确
if [ -f "$DB_PATH" ]; then
    chmod 644 $DB_PATH
    chown www:www $DB_PATH
fi

# 启动服务
systemctl start $SERVICE_NAME

# 等待服务启动
sleep 3

# 检查服务状态
echo "检查服务状态..."
if systemctl is-active --quiet $SERVICE_NAME; then
    echo "✅ 服务启动成功"
    systemctl status $SERVICE_NAME --no-pager -l
else
    echo "❌ 服务启动失败，查看日志："
    journalctl -u $SERVICE_NAME -n 20 --no-pager
fi

echo ""
echo "部署完成！"
echo "应用运行在: http://127.0.0.1:5000"
echo "请配置Nginx反向代理到此地址"
echo ""
echo "如果遇到数据库权限问题，请执行以下命令："
echo "sudo chown -R www:www $PROJECT_PATH"
echo "sudo chmod -R 755 $PROJECT_PATH"
echo "sudo chmod 644 $DB_PATH" 